use crate::prelude::*;
use crate::util;

#[derive(Clone, Debug)]
pub struct AsAspCodec<T: Codec>(T);

impl<T: Codec> AsAspCodec<T> {
    pub fn new(v: T) -> Self {
        Self(v)
    }

    pub fn inner(&self) -> &T {
        &self.0
    }

    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.0
    }

    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T: Codec> From<T> for AsAspCodec<T> {
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl<T: Codec> ecksport_codec::RpcCodec for AsAspCodec<T> {
    fn from_slice(buf: &[u8]) -> Result<Self, ecksport_codec::CodecError> {
        // FIXME use newer error variant
        let v = util::decode::<T>(buf)
            .map_err(|_| ecksport_codec::CodecError::ContainerTooLarge(usize::MAX))?;
        Ok(Self(v))
    }

    fn fill_buf(&self, buf: &mut Vec<u8>) -> Result<(), ecksport_codec::CodecError> {
        // Maybe this probably shouldn't panic but let's not care for now.
        util::encode_into(&self.0, buf).expect("codec: encode rpc instance");
        Ok(())
    }
}
